package club.caihappy.store.controller;

import club.caihappy.store.controller.ex.*;
import club.caihappy.store.service.ex.*;
import club.caihappy.store.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**
 * Created by DELL on 2022/2/27
 * 控制层类的基类
 **/
public class BaseController {
    //操作成功的状态码
    public static final int OK = 200;

    //请求处理方法，这个方法的返回值就是需要传递给前端的数据
    //自动将异常对象传递给此方法的参数列表上

    /**
     * 本质上就是个异常拦截器，拦截所有经过ServiceException的异常，
     * 只要报出异常，就会进入下方函数
     *
     * @param e
     * @return
     */
    @ExceptionHandler({ServiceException.class, FileUploadException.class})//用于统一处理抛出的异常
    public JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<>(e);
        if (e instanceof UsernameDuplicatedException) {
            //注册时用户名已存在异常
            result.setState(5000);
            /*
            result.setMessage(e.getMessage());
            JsonResult实例化时构造方法将throwable对象传入构造方法，message信息被导入,在此就不需要再导一遍
            */
        } else if (e instanceof InsertException) {
            //注册时发生未知异常
            result.setState(5000);
        } else if (e instanceof UserNotFoundException) {
            //用户不存在
            result.setState(5001);
        } else if (e instanceof PasswordNotMatchException) {
            //登录密码不正确
            result.setState(5002);
        } else if (e instanceof UpdateException) {
            //更新数据时产生未知异常
            result.setState(5003);
        } else if (e instanceof AddressCountLimitException) {
            //收货地址数量超出限制异常
            result.setState(5004);
        } else if (e instanceof AccessDeniedException) {
            //非法数据访问
            result.setState(5005);
        } else if (e instanceof AddressNotFoundException) {
            //收货地址不存在
            result.setState(5006);
        } else if (e instanceof DeleteException) {
            //删除数据时产生未知异常
            result.setState(5007);
        } else if (e instanceof FileEmptyException) {
            result.setState(6001);
        } else if (e instanceof FileSizeException) {
            result.setState(6002);
        } else if (e instanceof FileTypeException) {
            result.setState(6003);
        } else if (e instanceof FileStateException) {
            result.setState(6004);
        } else if (e instanceof FileUploadIOException) {
            result.setState(6005);
        } else if (e instanceof ProductNotFoundException) {
            result.setState(7001);
        } else if (e instanceof CartNotFoundException) {
            result.setState(7002);
        }
        return result;
    }

    //获取session对象中的Uid
    protected final Integer getUidFromSession(HttpSession session) {
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    //获取当前登录用户的Username
    protected final String getUsernameFromSession(HttpSession session) {
        return session.getAttribute("username").toString();
    }


}
